const koaRouter = require('koa-router')

const {Schema,model} = require('mongoose')
const uuid =require('node-uuid')
const {generateToken,getDecryptToken} = require('../config')
const router=koaRouter({
    prefix: '/koa'
})
//生成登录表的模型
var UserSchema=new Schema({
    uid:{type:String},
    username:{type:String},
    account:{type:String},
    password:{type:String},
    isNewUser:{type:Boolean,default:true}
})

const User=model('user',UserSchema);



router.post('/login',async(ctx,next)=>{
    const {request,response} =ctx
    const {account,password} = request.body
    const res= await findUser({account})
    if(res.length>0){
        //根据用户的account以及password生成token
        const token = generateToken(JSON.stringify({account:res[0].account,password:res[0].password}))
        const editres= await updateUser({account},{isNewUser:false})
       
        console.log(editres)
        ctx.body={
            code:200,
            data:{
                ...res[0],
                token,
                msg:'登录成功'
            }
        }
    }else{
        ctx.body={
            code:400,
            data:{
                msg:'账号或密码错误'
            }
        }
    }

    // console.log(ctx.req)
    
})


router.post('/register',async(ctx,next)=>{
    const {request,response} =ctx
    const {account,username,password} = request.body

      const res= await  findUser({account})
        
            if(res.length!=0){
                // console.log('xxx')
                ctx.body={
                    code:400,
                    data:{
                        msg:'已经存在该用户'
                    }
                }
            }else{
                const user = new User({username,account,password,uid:uuid.v1()})
               
                await user.save()
                
                    ctx.body={
                        code:200,
                        data:{
                            msg:'创建用户成功'
                        }
                    }
                
            } 
        
})

//查找用户
function findUser(params){
    return User.find(params)
}

//修改用户信息
function updateUser(params,newData){
    return User.update(params,newData)
}


module.exports={
    loginRouter:router,
    findUser
}